<?php


namespace Modules\Auth\Http\Controllers\Admin;


use App\Exceptions\BusinessException;
use App\Helpers\CodeResponse;
use App\Http\Controllers\Admin\ApiController;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Modules\Admin\Entities\Admin;
use Modules\Admin\Services\AdminService;
use Modules\Auth\Http\Requests\Admin\AuthRequest;
use Modules\Auth\Http\Requests\RefreshTokenRequest;
use Modules\Auth\Services\TokenService;

class AuthController extends ApiController
{
    protected ?array $except = ['login', 'refreshToken'];

    public function login(AuthRequest $request)
    {
        if (env("LOGIN_CAPTCHA", false)) {
            // 开启登录验证码
            $key = $request->get('captcha_token');
            if (Cache::get($key) != 'pass') {
                throw new BusinessException(CodeResponse::VERIFICATION_CODE_FAIL, "请先完成登录验证！");
            }
        }

        $func = function () use ($request) {
            if (!AdminService::getInstance()->AccountPasswordVerification($request->username, $request->password)) {
                throw new BusinessException(CodeResponse::ACCOUNT_PASSWORD_ERROR);
            }
            Admin::query()->where('username', $request->username)->update([
                'last_login_ip' => request()->getClientIp(),
                'last_login_time' => Carbon::now(),
            ]);
        };
        $data = TokenService::getInstance()->Login(
            $request->username,
            $request->password,
            config('auth.admin'),
            $func
        );
        return $this->success($data);
    }

    public function logout()
    {
        TokenService::getInstance()->logout($this->admin);
        return $this->success();
    }

    public function refreshToken(RefreshTokenRequest $request)
    {
        return TokenService::getInstance()->RefreshToken($request->refresh_token, config('auth.admin'));
    }
}
